package com.woniuxy.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.nimbusds.jose.JOSEException;
import com.woniuxy.entity.User;
import com.woniuxy.mapper.UserMapper;
import com.woniuxy.service.UserService;
import com.woniuxy.util.JWTUtil;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author ：CuiYC
 * @description：
 * @date ：Created in 2025/3/27 9:41
 * @modified By：
 */
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public ResponseData<?> login(User user) throws JOSEException {
        //根据账号查询用户信息
        User userInfo = userMapper.selectByAccount(user);
        //查询结果是否空
        if(userInfo == null){
            return ResponseData.fail(ResponseEnum.LOGIN_ERROR);
        }
        //校验前后端密码
        String md5PS = SecureUtil.md5(user.getPassword());
        if(!md5PS.equals(userInfo.getPassword())){
            return ResponseData.fail(ResponseEnum.LOGIN_ERROR);
        }
        //生成jwt
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put("userId",userInfo.getUserId());
        userMap.put("account",userInfo.getAccount());
        userMap.put("nickname", userInfo.getNickname());
        String jwt = JWTUtil.createJWT(userMap);
        //返回结果
        redisTemplate.opsForValue().set("JWT:"+userInfo.getUserId(), jwt, 15, TimeUnit.DAYS);
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("jwt", jwt);
        resultMap.put("userInfo", userInfo);
        return ResponseData.ok(resultMap);
    }
}
